<template>
  <el-dialog title="检测频率" v-model="visible" width="400px" @close="onClose">
    <el-form ref="formRef" :model="formParams" label-width="80px">
      <el-form-item
        label="检测频率"
        prop="frequency"
        :rules="[{ required: true, message: '', trigger: 'blur' }]"
      >
        <el-input-number
          @mousewheel.native.prevent
          v-model="formParams.frequency"
          :precision="0"
          controls-position="right"
          :min="1"
          :max="1440"
        />
        分/次
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleAction(false)">取消</el-button>
      <el-button :loading="submit" type="primary" @click="handleAction(true)"> 确认 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { updateFrequencyApi } from '@/api/device'

const emit = defineEmits(['refresh'])
const formRef = ref(null)
const visible = ref(false)
const submit = ref(false)
const formParams = reactive({
  machineId: '',
  frequency: null
})

function handleAction(confirm) {
  if (confirm) {
    formRef.value.validate((valid) => {
      if (valid) {
        submit.value = true
        updateFrequencyApi(formParams)
          .then(() => {
            onClose()
            ElMessage({
              type: 'success',
              message: '操作成功'
            })
            emit('refresh')
          })
          .catch((err) => {
            submit.value = false
          })
      }
    })
  } else {
    onClose()
  }
}

function onClose() {
  formRef.value.resetFields()
  submit.value = false
  visible.value = false
}
const init = (machineId, tempFrequency) => {
  formParams.machineId = machineId
  formParams.frequency = tempFrequency ? tempFrequency : null
  visible.value = true
}

defineExpose({
  init
})
</script>

<style lang="scss" scoped></style>
